package com.sxbbc.common.core.service.system.redis.listener;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.date.DateUtil;
import com.sxbbc.common.core.entity.jz.OrderDetail;
import com.sxbbc.common.core.entity.jz.OrderMain;
import com.sxbbc.common.core.entity.jz.ProSkuDetail;
import com.sxbbc.common.core.enums.OperationTypeEnums;
import com.sxbbc.common.core.enums.OrderStatusEnums;
import com.sxbbc.common.core.service.IActivitySeckillDetailService;
import com.sxbbc.common.core.service.IOrderDetailService;
import com.sxbbc.common.core.service.IOrderMainService;
import com.sxbbc.common.core.service.IOrderSeckillConfigService;
import com.sxbbc.common.core.service.IProSkuDetailService;

/**
 * 订单定时处理逻辑
 *
 * @author arno
 */
@Service
public class OrderListerService {

    @Autowired
    private IOrderMainService iOrderMainService;
    @Autowired
    private IOrderDetailService iOrderDetailService;
    @Autowired
    private IOrderSeckillConfigService iOrderSeckillConfigService;
    @Autowired
    private IProSkuDetailService iProSkuDetailService;
    @Autowired
    private IActivitySeckillDetailService iActivitySeckillDetailService;

    /**
     * 定时处理订单失效
     *
     * @param orderCode
     */
    public void handleOrderTimeout(String orderCode) {
        OrderMain main = iOrderMainService.getByOrderCode(orderCode);
        if (main != null) {
            //如果是待支付状态  修改为已取消
            if (CalcuUtils.getInstance().isEquals(OrderStatusEnums.COMFIRE.getId(), main.getOrderStatus())) {
                main.setOrderStatus(OrderStatusEnums.CANCEL.getId());
                main.setCancelTime(DateUtil.getInstance().currentDate());
                iOrderMainService.updateById(main);

                List<OrderDetail> list = iOrderDetailService.listByOrderCode(orderCode);
                for (OrderDetail l : list) {
                    handleQty(l);
                }
            }
        }
    }

    /**
     * 处理库存
     *
     * @param l
     */
    public void handleQty(OrderDetail l) {
        //归还库存
        ProSkuDetail sku = iProSkuDetailService.getById(l.getProDetailId());
        sku.setId(l.getProDetailId());
        sku.setQty(l.getQty());
        sku.setOperationType(OperationTypeEnums.ADD_QTY.getId());
        iProSkuDetailService.updateQtyVersion(sku);

    }
}
